let btnLogin = document.getElementById("btn-login");
let lineAccount = document.getElementById("lineAccount");
let inputAccount = document.getElementById("account");
let linePassword = document.getElementById("linePassword");
let inputPwd = document.getElementById("password");
let msgBox = document.getElementById("msg-box");
let handled = false;   //标识键盘事件是否被处理
let timer = null;      //弹层动画定时器
let sysUser = {
    account:"",
    password:""
};
inputAccount.oninput = (event)=>{
    let account = event.target.value;
    sysUser.account = account;
    if(!account){
        setInvalid(lineAccount,inputAccount)
    }else{
        setValid(lineAccount,inputAccount)
    }
}
inputPwd.oninput = (event)=>{
    let password = event.target.value;
    sysUser.password = password;
    if(!password){
        setInvalid(linePassword,inputPwd)
    }else{
        setValid(linePassword,inputPwd)
    }
}
btnLogin.onclick=login;
btnLogin.onclick=login;
window.addEventListener("keydown", function (event) {
    if (handled) {
        // 如果事件已处理，则禁止“双重操作”
        event.preventDefault();
    }
    if (event.key !== undefined) {
        if(event.key.toLowerCase() === "enter"){
            login();
        }
    } else if (event.keyCode === 13) {
        login();
    }
}, true);
function login(){
    let flag = true;
    if(!sysUser.account){
        setInvalid(lineAccount,inputAccount);
        flag = false
    }
    if(!sysUser.password){
        setInvalid(linePassword,inputPwd);
        flag = false
    }
    if(flag){
        handled = true;
        btnLogin.value = "登录中...";
        btnLogin.disabled = "disabled";
        $http.post("login",sysUser).then(res=>{
            if(res.code !== 200){
                handled = false;
                btnLogin.value = "登录";
                btnLogin.removeAttribute("disabled");
                showMessageBox(res.msg);
            }else{
                window.location.href = reqBaseUrl+"index";
            }
        })
    }
}
function setInvalid(dom1,dom2) {
    dom1.style.borderColor = "#f56c6c";
    dom2.classList.add("invalid");
}
function setValid(dom1,dom2) {
    dom1.style.borderColor = "transparent";
    dom1.style.borderBottomColor = "#484856";
    dom2.classList.remove("invalid");
}
function showMessageBox(msg) {
    msgBox.innerText = msg;
    msgBox.style.zIndex = 1;
    let opacity = 0;
    let time = 0;
    if(timer !== null){
        clearInterval(timer)
    }
    timer = setInterval(()=>{
        time++;
        if(time < 50){
            opacity+=5;
            msgBox.style.opacity=opacity/50;
        }else if(time > 300){
            opacity-=5;
            msgBox.style.opacity=opacity/50;
            if(opacity === 0){
                clearInterval(timer);
                msgBox.style.zIndex = -1;
            }
        }
    },10);
}